package com.resign.carl.observer.api.impl;

import com.google.common.collect.Lists;
import com.resign.carl.observer.api.DisplayElement;
import com.resign.carl.observer.api.Observer;
import com.resign.carl.observer.api.Subject;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;

/**
 * Created by carl.zhao on 2016/6/13.
 */
public class StatisticsDisplay implements Observer,DisplayElement {
    private float temperature;
    private Subject weatherDate;
    private List<Float> temperatures = Lists.newArrayList();
    public StatisticsDisplay(Subject weatherDate){
        this.weatherDate = weatherDate;
    }
    @Override
    public void display() {
        if(CollectionUtils.isEmpty(temperatures)){
            System.out.println("temperature is null." );
        }
        float avgTemperature = getAvgValue(temperatures).floatValue();
        float maxTemperature = Collections.max(temperatures);
        float minTemparature = Collections.min(temperatures);

        System.out.println("Avg/Max/Min temperature = " + avgTemperature + "/" + maxTemperature + "/" + minTemparature);
    }

    @Override
    public void update(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        temperatures.add(temperature);
        display();
    }

    private BigDecimal getAvgValue(List<Float> temperatures){
        if(CollectionUtils.isEmpty(temperatures)){
            return BigDecimal.ZERO;
        }
        BigDecimal totalValue = BigDecimal.ZERO;
        for(Float temperature : temperatures){
            totalValue = totalValue.add(new BigDecimal(String.valueOf(temperature)));
        }
        return totalValue.divide(new BigDecimal(temperatures.size()), RoundingMode.HALF_UP);
    }
}
